#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1

BIN=/etc/subconverter/subconverter
PID=""

getPid(){
        ps | grep subconverter > /tmp/_subconverter_pid
        sed -i '/grep/d' /tmp/_subconverter_pid
	sed -i '/bin\/sh/d' /tmp/_subconverter_pid
        sed -i "s/^[ \s]\{1,\}//g;s/[ \s]\{1,\}$//g" /tmp/_subconverter_pid
	local pid=$(cat /tmp/_subconverter_pid| cut -d ' ' -f1)
	PID=$pid
	#echo PID is $pid === $PID
	rm -rf /tmp/_subconverter_pid
}

start_service() {
	getPid
	local pid=$PID
	if [ ! -z "$pid" ]; then
		echo "Subconverter has already run, PID is "$pid
		return 0
	fi
	[ ! -e /etc/subconverter/subconverter ] && cp /usr/bin/subconverter /etc/subconverter/subconverter
	procd_open_instance
	procd_set_param command $BIN
	procd_set_param respawn
	procd_set_param stderr 1
	procd_close_instance
	echo Subconverter started.
}

stop_service() {
	getPid
	local pid=$PID
	if [ ! -z "$pid" ]; then
		echo Found subconverter process, which PID is $pid
		kill $pid
		echo Subconverter process has been terminated.
	else
		echo No subconverter process found.
		return 0
	fi
}

reload_service() {
	stop
	start
}